from django.shortcuts import render,redirect
from user.models import User, Address
from django.core.urlresolvers import reverse
from django.views.generic import View
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.conf import settings
from celery_tasks.tasks import send_registar_active_email
from django.core.mail  import send_mail
from django.http  import HttpResponse
from django.contrib.auth import authenticate,login,logout
import re


# 注册
# 注册页面
class RegistarView(View):
    # 注册页面
    def get(self, request):
        return render(request, 'registar.html')

    def post(self,request):
        # 获取数据
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        allow = request.POST.get('allow')
        # 效验数据
        if not all([username, password, email]):
            return render(request, 'registar.html', {'errmsg': '数据不完整'})
        # 效验邮箱格式
        if not re.match('^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'registar.html', {'errmsg': '邮箱格式不正确'})
        # 判断用户是否勾选用户协议
        if not allow == 'on':
            return render(request, 'registar.html', {'errmsg': '请勾选用户协议'})

        # 判断用户是否存在
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # 用户不存在
            user = None

        if user:
            # 用户已存在
            return render(request, 'registar.html', {'errmsg': '用户已存在'})

        # 进行业务处理：
        user = User.objects.create_user(username, email, password)
        user.is_active = 0
        user.save()

        # 发送激活邮件，包含激活链接: http://127.0.0.1:8000/user/active/3
        # 激活链接中需要包含用户的身份信息, 并且要把身份信息进行加密

        # 加密用户的身份信息，生成激活token
        serializer = Serializer(settings.SECRET_KEY, 3600)
        info = {'confirm': user.id}
        token = serializer.dumps(info)
        token = token.decode()

        # 发邮件
        send_registar_active_email.delay(email, username, token)

        # 返回应答
        return redirect(reverse('goods:index'))


